package com.fy.module.user.controller;

import com.fy.common.exception.JWTParseException;
import com.fy.common.util.JwtUtils;
import com.fy.common.util.RsaUtils;
import com.fy.common.vo.MyUser;
import com.fy.common.vo.ResultVo;
import com.fy.module.user.UserDto;
import com.fy.module.user.entity.User;
import com.fy.module.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import java.security.PublicKey;

@RestController
@RequestMapping("user")
@CrossOrigin
@Api(description = "用户登录模块")
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("login")
    @ApiOperation("用户登录")
    public ResultVo login(@ApiParam("用户登录账户") @RequestBody UserDto user){
        return userService.login(user);
    }

    @GetMapping("logout")
    @ApiOperation("用户退出")
    public ResultVo logout(){
        return null;
    }

    @GetMapping("verify")
    @ApiOperation("用户校验token的合法性")
    public ResultVo verify(@RequestHeader("token") String token){
        try{
//            PublicKey publicKey = RsaUtils.getPublicKey(ResourceUtils.getFile("classpath:pub_rsa").getPath());
            PublicKey publicKey = RsaUtils.getPublicKey(RsaUtils.readBytes3(new ClassPathResource("pub_rsa").getInputStream()));
            User user = (User) JwtUtils.getInfoFromToken(token, publicKey, User.class);
            return new ResultVo(true, "valid token");
        } catch (Exception e) {
            if(e instanceof JWTParseException){
                //非法令牌
                return new ResultVo(false, "invalid token");
            }else{
                return new ResultVo(false, "");
            }
        }

    }
}
